/**
 * Copyright (C)2015 - 2016 , CITIC HENDDA, Inc.
 */
package cc.yihy.web.controller;

import cc.yihy.web.shiro.authc.BUsernamePasswordToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @ClassName:LoginController.java
 * @Description:
 * @Author: yihy
 * @Since: 2016-8-1
 * @Version: 1.0
 */
@Controller
@RequestMapping("/user")
public class LoginController {
    private final Logger log = LoggerFactory.getLogger(this.getClass());


    @RequestMapping(value = "/login.html", method = {RequestMethod.POST})
    public String login(@RequestParam("username") String userName, @RequestParam("password") String password, @RequestParam(value = "redirect", defaultValue = "index") String redirect) {
        Subject currentUser = SecurityUtils.getSubject();


        //创建token
        BUsernamePasswordToken token = new BUsernamePasswordToken(userName, password);

        try {
            //登录
            currentUser.login(token);
        } catch (AuthenticationException e) {
            log.error("登录失败",e);
            return "user/login";
        }


        //检查是否登录成功
        if (!currentUser.isAuthenticated()) {
            return "redirect:" + redirect;
        }
        return "user/user/login";
    }


}
